package com.jd.home.common;

import cn.itcast.common.web.session.SessionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前台   拦截器
 * @author lx
 *
 */
public class SpringmvcInterceptor implements HandlerInterceptor {

	@Autowired
	private SessionProvider sessionProvider;
	
	//必须拦截的请求
	public static final String URL_INTERCEPTOR = "/buyer";
	//管理员
	private Integer adminId;
	public void setAdminId(Integer adminId) {
		this.adminId = adminId;
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		if(null != adminId){
			//开发阶段
			sessionProvider.setAttributeForUserName(request, response,
					Constants.USER_SESSION, "fbb2014");
			request.setAttribute("isLogin", true);
			
		}else{
			
			//1:判断请求必须登陆的
			//  http://localhost:8081/buyer/trueBuy.shtml
			// /buyer/trueBuy.shtml
			String requestURI = request.getRequestURI();
			if(requestURI.startsWith(URL_INTERCEPTOR)){
				//必须登陆
				//判断用户是否登陆
				String username = sessionProvider.getAttribute(request, response, Constants.USER_SESSION);
				if(null != username){
					request.setAttribute("isLogin", true);
					return true;
				}else{
					request.setAttribute("isLogin", false);
					//重定向
					response.sendRedirect("/shopping/login.shtml?returnUrl=" + requestURI);
					return false;
				}
			}else{
				//可登陆可不登陆
				//判断用户是否登陆
				String username = sessionProvider.getAttribute(request, response, Constants.USER_SESSION);
				if(null != username){
					request.setAttribute("isLogin", true);
				}else{
					request.setAttribute("isLogin", false);
				}
				
				
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
